<template>

	<BreadCrumb pathOne="课程管理" pathTwo="视频管理"></BreadCrumb>

	<el-form :inline="true" :model="queryInfo" class="demo-form-inline" size="large">
		<el-form-item label="视频名称">
			<el-input v-model="queryInfo.title" placeholder="请输入视频名称" clearable />
		</el-form-item>
		<!-- <el-form-item label="所属课程">
				<el-input v-model="queryInfo.courseId" placeholder="请输入所属课程" clearable />
			</el-form-item> -->
		<el-form-item>
			<el-button type="primary" @click="search">搜索</el-button>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="openDialog('add')">新增视频</el-button>
		</el-form-item>
		<el-form-item>
			<el-button type="danger" @click="batchDelete">
				批量删除
			</el-button>
		</el-form-item>
	</el-form>

	<el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
		@selection-change="handleSelectionChange" :loading="loading" border class="category-table">
		<el-table-column type="selection" width="55" />
		<el-table-column prop="id" label="视频ID" width="100" align="center" />
		<el-table-column prop="title" label="视频名称" min-width="180" align="center" show-overflow-tooltip />
		<el-table-column label="视频文件">
			<template #default="scope">
			        <video
			            :src="getOssImageUrl(scope.row.videoUrl)"
			            alt="加载失败"
			            style="width: 100px;height: 100px; line-height: 100px ;border: 1px;background-color: #f5f7fa; cursor: pointer"
			        ></video>
			      </template>
		</el-table-column>
		<el-table-column label="视频时长" width="120" align="center">
		  <template #default="scope">
		    <!-- 使用格式化方法转换时长 -->
		    {{ formatDuration(scope.row.durationMs) }}
		  </template>
		</el-table-column>
		<el-table-column prop="course.title" label="所属课程" min-width="150" align="center" show-overflow-tooltip />

		<el-table-column label="操作" width="240" align="center">
			<template #default="scope">
				<div style="display: flex; justify-content: center; gap: 16px;">
					<el-button size="large" type="primary" @click="openDialog('edit', scope.row)">编辑</el-button>
					<el-button size="large" type="danger" @click="deleteVideo(scope.row.id)">删除</el-button>
				</div>
			</template>
		</el-table-column>
	</el-table>

	<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
		:current-page="queryInfo.pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="queryInfo.pageSize"
		layout="total, sizes, prev, pager, next, jumper" :total="total" style="margin-top: 20px" />

	<el-dialog v-model="dialogVisible" :title="dialogTitle">
		<el-form :model="form" label-width="110px" class="dialog-form" size="large">
			<el-form-item label="视频名称" required>
				<el-input v-model="form.title" placeholder="请输入视频名称" />
			</el-form-item>
			<!-- <el-form-item label="视频时长" required>
				<el-input v-model="form.videoTime" autocomplete="off" maxlength="20" show-word-limit />
			</el-form-item> -->
			<!-- <el-form-item label="视频图片">
				<el-upload class="avatar-uploader" action="http://your-backend-url/upload" :show-file-list="false"
					:before-upload="beforeUpload" :on-success="handleUploadSuccess" :on-error="handleUploadError"
					:data="uploadData">
					<img v-if="form.videoUrl" :src="form.videoUrl" class="avatar" />
					<el-icon v-else>
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item> -->
			<el-form-item label="视频文件">
				
				<el-upload :action="getUploadUrl()" list-type="text" :on-success="handleSuccess"
					:limit="1" :on-preview="handlePictureCardPreview" :file-list="fileList" :on-remove="handleRemove">
					<el-icon style="width: 128px; height: 128px;border: 1px dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
						<Plus />
					</el-icon>
				</el-upload>
				<!-- 放大预览组件: 和官网一致 -->
				<!-- <el-dialog v-model="dialogVisibleImage">
					<img w-full :src="dialogImageUrl" alt="Preview Image" />
				</el-dialog> -->
				<!-- 视频预览区域：显示视频封面（第一帧） -->
				</el-form-item>
				<el-form-item>
				    <div v-if="form.videoUrl">
				      <video 
				        :src="getOssImageUrl(form.videoUrl)" 
				        width="320" 
				        height="240" 
				        controls  
				        poster  
				      ></video>
				    </div>
			</el-form-item>
			<el-form-item label="课程">
				<el-select @clear="form.courseId=''" clearable v-model="form.courseId" placeholder="请选择所属课程"
					size="large" style="width: 240px">
					<el-option v-for="(item,index) in courseAll" :value="item.id" :label="item.title" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
	import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus';
	import BreadCrumb from "../../components/BreadCrumb.vue"
	import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
	import type { UploadFile } from 'element-plus'
	import { OSS_CONFIG, getOssImageUrl,getUploadUrl } from '../../util/ossConfig';
	
	// 时长格式化方法：将毫秒转换为 hh:mm:ss
	const formatDuration = (ms) => {
	  // 处理无效值
	  if (!ms || ms <= 0) return '00:00:00';
	  
	  // 转换毫秒为总秒数
	  const totalSeconds = Math.floor(ms / 1000);
	  
	  // 计算时、分、秒
	  const hours = Math.floor(totalSeconds / 3600);
	  const minutes = Math.floor((totalSeconds % 3600) / 60);
	  const seconds = totalSeconds % 60;
	  
	  // 补零操作，确保每位都是两位数
	  const pad = (num) => num.toString().padStart(2, '0');
	  
	  return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
	};

	

	// 查询参数
	const queryInfo = reactive({
		title: '',
		pageSize: 10,
		pageNum: 1,
	});

	// 表格数据和分页
	const tableData = ref([]);
	const total = ref(0);
	const loading = ref(false);

	// 选择相关
	const multipleTableRef = ref<TableInstance>();

	const axios = getCurrentInstance().appContext.config.globalProperties.axios;

	// 弹窗表单
	const dialogVisible = ref(false);
	const dialogTitle = ref('新增视频');
	let form = reactive({
		id: '',
		title: '',
		videoUrl: '',
		durationMs: '',
		courseId: ''
	});
	let dialogMode = 'add';

	// 查询列表
	const queryDataList = () => {
		loading.value = true;
		axios.get('courseVideo/page', {
			params: queryInfo
		})
			.then((response) => {
				if (response && response.code === 200) {
					tableData.value = response.data.list || [];
					total.value = response.data.total || 0;
					// console.log('tableData.value:',tableData.value);
				} else {
					ElMessage.error(response.message || '查询失败');
				}
			})
			.catch(() => {
				ElMessage.error('网络请求错误，请检查网络连接或服务器状态');
			})
			.finally(() => {
				loading.value = false;
			});
	};
	const courseAll = ref([])
	const getCourseAll = () => {
		axios.get('course').then((resp) => {
			if (resp.code == 200) {
				console.log(resp);
				courseAll.value = resp.data;
			}
		})
	}
	onMounted(() => {
		queryDataList();
		getCourseAll();
	});

	// 搜索
	const search = () => {
		queryInfo.pageNum = 1;
		queryDataList();
	};

	// 分页
	const handleSizeChange = (size : number) => {
		queryInfo.pageSize = size;
		queryDataList();
	};
	const handleCurrentChange = (num : number) => {
		queryInfo.pageNum = num;
		queryDataList();
	};

	// 选择
	const multipleSelection = ref('')
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => item.id).join(',')
	}

	// 打开弹窗
	function openDialog(mode : 'add' | 'edit', row ?: any) {
		dialogMode = mode;
		if (mode == 'add') {
			dialogTitle.value = '新增视频';
			form.id = '';
			form.title = '';
			form.durationMs = '';
			form.videoUrl = '';
			form.courseId = '';
			fileList.value = [];
		} else if (mode == 'edit' && row) {
			dialogTitle.value = '编辑视频';
			axios.get(`courseVideo/${row.id}`).then((resp : any) => {
				if (resp.code === 200) {
					// form=resp.data
					form.id = resp.data.id;
					form.title = resp.data.title;
					form.videoUrl = resp.data.videoUrl;
					form.durationMs = resp.data.durationMs;
					form.courseId = resp.data.courseId;
					if (resp.data.videoUrl) {
						fileList.value = [{
							url: getOssImageUrl(resp.data.videoUrl)
						}]
					} else {
						fileList.value = []
					}
				} else {
					ElMessage.error('请求失败');
				}
			});


		}
		dialogVisible.value = true;
	}

	// 上传相关
	const uploadData = reactive({}) // 可根据需要传递额外参数

	function beforeUpload(file) {
		// 可在此校验文件类型/大小
		return true;
	}
	function handleUploadSuccess(response) {
		// 假设后端返回图片url为 response.url
		form.videoUrl = response.url;
		ElMessage.success('图片上传成功');
	}
	function handleUploadError() {
		ElMessage.error('图片上传失败');
	}

	// 新增/编辑提交
	function submitForm() {
		if (!form.title.trim()) {
			ElMessage.warning('请输入视频名称');
			return;
		}
		// if (!form.courseName.trim()) {
		// 	ElMessage.warning('请输入所属课程');
		// 	return;
		// }
		if (!form.courseId) {
			ElMessage.warning('请输入课程ID');
			return;
		}
		if (dialogMode === 'add') {
			axios.post('courseVideo', {
				title: form.title,
				videoUrl: form.videoUrl,
				durationMs: form.durationMs,
				courseId: form.courseId
			}).then((resp : any) => {
				if (resp.code === 200) {
					ElMessage.success('新增成功');
					dialogVisible.value = false;
					queryDataList();
				} else {
					ElMessage.error(resp.message || '新增失败');
				}
			});
		} else if (dialogMode === 'edit') {
			axios.put('courseVideo', {
				id: form.id,
				title: form.title,
				videoUrl: form.videoUrl,
				durationMs: form.durationMs,
				courseId: form.courseId
			}).then((resp : any) => {
				if (resp.code === 200) {
					ElMessage.success('编辑成功');
					dialogVisible.value = false;
					queryDataList();
				} else {
					ElMessage.error(resp.message || '编辑失败');
				}
			});
		}
	}

	// 删除
	function deleteVideo(id : number) {
		ElMessageBox.confirm('确定要删除该视频吗？', '提示', {
			type: 'warning'
		}).then(() => {
			axios.delete(`courseVideo/${id}`).then((resp : any) => {
				if (resp.code === 200) {
					ElMessage.success('删除成功');
					queryDataList();
				} else {
					ElMessage.error(resp.message || '删除失败');
				}
			});
		});
	}

	// 批量删除
	function batchDelete() {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择要删除的视频');
			return;
		}
		ElMessageBox.confirm('确定要批量删除选中的视频吗？', '提示', {
			type: 'warning'
		}).then(() => {
			axios.delete(`courseVideo?ids=${multipleSelection.value}`).then((resp : any) => {
				if (resp.code === 200) {
					ElMessage.success('批量删除成功');
					queryDataList();
				} else {
					ElMessage.error(resp.message || '批量删除失败');
				}
			});
		});
	}
	

	const disabled = ref(false)


	const handleDownload = (file : UploadFile) => {
		console.log(file)
	}
	
	// 图片上传
	    const dialogImageUrl = ref('') // 图片预览框的地址
	    const dialogVisibleImage = ref(false) // 控制图片预览框是否显示
	    const fileList = ref([])
	    // 上传成功的回调，res服务器响应的数据
	    const handleSuccess = (res, file) => {
	        console.log("文件上传成功", res);
	        // 判断是否为视频（返回结果包含durationMs）
	        if (res.data.durationMs !== undefined) {
	            form.videoUrl = res.data.url;  // 视频地址
	            form.durationMs = res.data.durationMs;  // 视频时长（毫秒）
	        } else {
	            // 图片处理（原有逻辑）
	            form.videoUrl = res.data;
	        }
	    };
	    // 处理删除图片
	    const handleRemove = (file, fileList) => {
	        form.videoUrl = ''
	    }
	    // 处理图片预览
	    const handlePictureCardPreview = (file) => {
			console.log("file:",file)
	        dialogImageUrl.value = file.url;
	        dialogVisibleImage.value = true;
	    }
</script>

<style scoped>
	/* .top {
	background-color: #f8f9fa;
	padding: 12px 20px;
	margin-bottom: 15px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
} */
	/* .el-breadcrumb {
	max-width: 1200px;
	margin: 0 auto;
} */
	/* .middel {
	background: #fff;
	padding: 20px;
	margin-bottom: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
} */
	.demo-form-inline {
		display: flex;
		align-items: center;
		gap: 15px;
	}

	.demo-form-inline .el-form-item {
		margin-right: 20px;
	}

	.demo-form-inline .el-input,
	.demo-form-inline .el-select {
		width: 220px;
	}

	/* .el-button {
	min-width: 100px;
}
.el-button + .el-button {
	margin-left: 10px;
} */
	/* .content {
	background: #fff;
	padding: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
} */
	/* .category-table {
	background: #fff;
	border-radius: 8px;
} */
	.el-table {
		margin-bottom: 20px;
	}

	.el-table__header-wrapper {
		border-radius: 6px 6px 0 0;
	}

	.el-table__body-wrapper {
		border-radius: 0 0 6px 6px;
	}

	/* .el-pagination {
	display: flex;
	justify-content: flex-end;
	margin-top: 30px !important;
} */
	.dialog-form {
		padding-top: 10px;
	}

	.avatar-uploader .avatar {
		width: 100px;
		height: 100px;
		display: block;
	}
	.video-cover-container {
	  position: relative;
	  width: 100px;  /* 与avatar大小一致 */
	  height: 100px;
	}
	.video-cover {
	  position: absolute;
	  top: 0;
	  left: 0;
	  width: 100%;
	  height: 100%;
	  opacity: 0;  /* 隐藏视频元素 */
	  pointer-events: none;  /* 禁止交互 */
	}
</style>